package cn.dsp.admin.controller;

import cn.dsp.admin.controller.ex.*;
import cn.dsp.admin.entity.UserRole;
import cn.dsp.admin.entity.admin.Admin;
import cn.dsp.admin.service.IAdminService;
import cn.dsp.admin.service.ex.ServiceException;
import cn.dsp.admin.utils.JsonResult;
import cn.dsp.admin.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("admin")
public class AdminController extends BaseController {

    @Autowired
    private IAdminService adminService;


    @RequestMapping("login")
    public JsonResult<Admin> login(String adminName, String password, HttpSession session){
        Admin data = adminService.login(adminName,password);
        session.setAttribute("adminId",data.getAdminId());
        session.setAttribute("adminName",data.getAdminName());
        session.setAttribute("storeId",data.getStoreId());
        return new JsonResult<>(SUCCESS,data);
    }

    @RequestMapping("reg")
    public JsonResult<Void> reg(Admin admin,HttpSession session){
        try {
            String createdUser = getAdminNameFromSession(session);
            Integer storeId = getStoreIdFromSession(session);
            adminService.reg(admin,createdUser,storeId);
        } catch (ServiceException e) {
            return new JsonResult<>(e);
        }
        return new JsonResult<>(SUCCESS);
    }

    @RequestMapping(path = "change_password")
    public JsonResult<Void> changePassword(@RequestParam("old_password") String oldPassword,
                                           @RequestParam("new_password") String newPassword, HttpSession session) {
        Integer adminId = getAdminIdFromSession(session);
        String adminName = getAdminNameFromSession(session);
        try {
            adminService.changePassword(adminId, adminName, oldPassword, newPassword);
        } catch (ServiceException e) {
            return new JsonResult<>(e);
        }
        return new JsonResult<>(SUCCESS);
    }

    /**
     * 允许上传的文件的最大大小
     */
    private static final long FILE_MAX_SIZE = 3*1024 * 1024;
    /**
     * 允许上传的文件的类型
     */
    private static final List<String> FILE_TYPES = new ArrayList<>();

    static {
        FILE_TYPES.add("image/jpeg");
        FILE_TYPES.add("image/png");
        FILE_TYPES.add("image/gif");
    }

    @PostMapping("change_avatar")
    public JsonResult<String> changeAvatar(@RequestParam("file") MultipartFile file,
                                           HttpSession session,HttpServletRequest request) {
        //检查：上传的文件是否为空
        if(file.isEmpty()){
            //是：没有选择文件，或者选择的文件是0字节的
            throw new FileEmptyException("没有选择文件，或者选择的文件是0字节的");
        }
        //检查：上传的文件大小
        if (file.getSize()>FILE_MAX_SIZE) {
            throw new FileSizeException("不允许上传超过"+FILE_MAX_SIZE/1024+"KB的文件");
        }
        //检查：上传的文件类型
        if (!FILE_TYPES.contains( file.getContentType())) {
            throw new FileTypeException("仅支持上传"+FILE_TYPES+"文件类型");
        }
        //上传到的文件
        String dirPath = request.getSession().getServletContext().getRealPath("upload");
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        //原文件名
        String originalFilename = file.getOriginalFilename();
        //扩展名
        String suffix = "";
        int index = originalFilename.lastIndexOf(".");
        if (index > 0) {
            suffix = originalFilename.substring(index);
        }
        //文件全名
        String filename = UUID.randomUUID().toString()+suffix;

        //保存到的文件
        File dest = new File(dir,filename);
        //保存用户上传的头像
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            throw new FileUploadStateException("文件可能已经被移动或者删除，不可访问到该文件");
        }catch (IOException e){
            e.printStackTrace();
            throw new FileUploadIOException("出现读写错误！");
        }
        //头像路径
        String avatar = "/upload/"+filename;
        System.out.println(dirPath);
        System.out.println(avatar);

        //获取用户信息
        Integer adminId = getAdminIdFromSession(session);
        String adminName = getAdminNameFromSession(session);
        //执行更新数据库
        //执行更新数据库
        adminService.changeAvatar(adminId,adminName,avatar);
        //返回结果
        return new JsonResult<>(SUCCESS,avatar);
    }
    /**管理员修改个人资料*/
    @PostMapping("change_info")
    public JsonResult<Void> changeInfo( Admin admin,HttpSession session) {
        //获取用户信息
        Integer adminId = getAdminIdFromSession(session);
        String adminName = getAdminNameFromSession(session);
        //执行更新数据库
        adminService.changeInfo(adminId,adminName,admin);
        return new JsonResult<>(SUCCESS);
    }

    /**管理员修改管理员资料
     *  http://localhost:8088/admin/change_admin_info?adminId=20&adminName=test&roleIds=1&roleIds=2&roleIds=7&roleIds=9
     * */
    //@PostMapping("change_admin_info")
    @GetMapping("change_admin_info")
    public JsonResult<Void> changeInfoAdmin( Admin admin,HttpSession session,Integer[] roleIds) {
        //获取管理员信息
        String modifiedUser = getAdminNameFromSession(session);
        Integer adminId = admin.getAdminId();
        //清空用户原有的角色
        adminService.deleteAllRole(adminId);
        for (Integer r: roleIds) {
            //创建一个rolePerm封装角色的权限
            UserRole userRole = new UserRole();
            userRole.setAdminId(adminId);
            userRole.setRoleId(r);
            //插入新的权限
            adminService.adminAddRole(userRole);
        }
        //执行更新数据库
        adminService.changeInfoByAdmin(admin,modifiedUser);
        return new JsonResult<>(SUCCESS);
    }

    /**显示个人资料*/
    //@RequestMapping(method = RequestMethod.GET,path = "get_by_uid")
    @GetMapping("get_by_adminId")
    public JsonResult<AdminVO> getByAdminId(HttpSession session){
        Integer adminId = getAdminIdFromSession(session);
        AdminVO data = null;
        try {
            data = adminService.getAdminVO(adminId);
        } catch (ServiceException e) {
            return new JsonResult<>(e);
        }
        return new JsonResult<>(SUCCESS, data);
    }

    /**显示*/
    @RequestMapping("get_admin_all")
    public JsonResult<List<Admin>> getAllAdmin(HttpSession session){
       Integer storeId = getStoreIdFromSession(session);
        List<Admin> data = adminService.getAllAdmin(storeId);
        //返回
        return new JsonResult<>(SUCCESS,data);
    }

    /**查找*/
    @RequestMapping("get_admin_like/{term}")
    public JsonResult<List<Admin>> getAdminByTerm(@PathVariable("term") String term,HttpSession session){
        Integer storeId = getStoreIdFromSession(session);
        List<Admin> data = adminService.getAdminByTerm(storeId,term);
        return new JsonResult<>(SUCCESS,data);
    }


    @RequestMapping("get_admin_by/{adminId}")
    public JsonResult<Admin> getByAdminId(@PathVariable("adminId") Integer adminId){
        Admin data = adminService.getByAdminId(adminId);
        return new JsonResult<>(SUCCESS,data);
    }

    /**显示 ----管理员编辑管理员资料*/
    @RequestMapping("get_adminVO_by/{adminId}")
    public JsonResult<AdminVO> getAdminVO(@PathVariable("adminId") Integer adminId){
        AdminVO data = null;
        try {
           data = adminService.getAdminVO(adminId);
        } catch (ServiceException e) {
            return new JsonResult<>(e);
        }
        return new JsonResult<>(SUCCESS,data);
    }

    @RequestMapping("delete_admin_by/{adminId}")
    public JsonResult<Void> deleteByAdminId(@PathVariable("adminId") Integer adminId){
        adminService.deleteByAdminId(adminId);
        return new JsonResult<>(SUCCESS);
    }
}
